package com.bayss.core.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Slf4j
public class TokenUtils {
    public static final String secret = "eyJhbGciOiJIUzI1NiJ9";

    /**
     * 生成Token
     *
     * @param userId   用户Id
     * @param outHours 有效期（小时）
     * @return
     * @throws IllegalArgumentException
     */
    public static String createToken(String claim, Integer userId, int outHours) throws IllegalArgumentException {
        Algorithm al = Algorithm.HMAC256(secret);
        Instant instant = LocalDateTime.now().plusHours(outHours).atZone(ZoneId.systemDefault()).toInstant();
        Date expire = Date.from(instant);
        String token = JWT.create()
                .withSubject("userInfo")
                .withClaim(claim, userId)
                .withExpiresAt(expire)
                .sign(al);
        return token;
    }

    /**
     * 验证Token是否有效
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static boolean verifyToken(String token) throws Exception {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        if (jwt.getExpiresAt().before(new Date())) {
            throw new JWTVerificationException("token已过期");
        }
        return true;
    }

    /**
     * 从Token中提取UserId
     *
     * @param token
     * @return
     */
    public static Integer getUserId(String token, String claim) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        Integer userId = jwt.getClaim(claim).asInt();
        return userId;
    }

    public static void main(String[] args) {
        String token = TokenUtils.createToken("user_id", 1, 1);
        System.out.println(token);
        int userId = TokenUtils.getUserId(token, "user_id");
        System.out.printf(userId + "");
    }
}
